package com.collect.zambia.zhiScene.zhiLogin;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.provider.Settings;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.TextView;

import androidx.work.ExistingPeriodicWorkPolicy;
import androidx.work.PeriodicWorkRequest;
import androidx.work.WorkManager;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.collect.zambia.R;
import com.collect.zambia.zhiBase.BaseActivity;
import com.collect.zambia.zhiBean.zhiReceive.ZHIRAppVersionEntity;
import com.collect.zambia.zhiBean.zhiReceive.ZHIRCheckInOutEntity;
import com.collect.zambia.zhiBean.zhiReceive.ZHIRLoginEntity;
import com.collect.zambia.zhiBean.zhiReceive.ZHIRUserCallRecordWarnEntity;
import com.collect.zambia.zhiBean.zhiReceive.ZHIRWorkAccountIdEntity;
import com.collect.zambia.zhiBean.zhiSend.ZHISLoginEntity;
import com.collect.zambia.zhiBean.zhiSend.ZHISWorkAccountIdEntity;
import com.collect.zambia.zhiBean.zhiSend.ZHISendEntity;
import com.collect.zambia.zhiCallLogWorker.ZHICallLogUploadWorker;
import com.collect.zambia.zhiGlobal.zhiAppSettings.ZHIProjectConfigs;
import com.collect.zambia.zhiGlobal.zhiAppSettings.ZHIProjectRouter;
import com.collect.zambia.zhiHelper.ZHIAdvertIDHelper;
import com.collect.zambia.zhiHelper.ZHIAppVersionHelper;
import com.collect.zambia.zhiHelper.ZHIMainProcessHelper;
import com.collect.zambia.zhiHelper.ZHICallLogHelper;
import com.collect.zambia.zhiScene.zhiCheckIn.ZHICheckInReduce;
import com.collect.zambia.zhiScene.zhiTelemarketing.zhiLogic.ZHITelemarketingFollowHelper;
import com.collect.zambia.zhiScene.zhiWidget.zhiDialog.ZHIDialogItemClickListener;
import com.collect.zambia.zhiScene.zhiWidget.zhiDialog.ZHIDialogMessage;
import com.collect.zambia.zhiScene.zhiWidget.zhiDialog.ZHIDialogPasswordUpdateSuccess;
import com.collect.zambia.zhiScene.zhiWidget.zhiDialog.ZHIDialogWorkAccountId;
import com.collect.zambia.zhiScene.zhiWidget.zhiInputView.ZHIInputEditView;
import com.collect.zambia.zhiScene.zhiWidget.zhiStepView.ZHINextStepView;
import com.collect.zambia.zhiUtils.PhoneAccountUtil;
import com.collect.zambia.zhiUtils.TextViewUtil;
import com.collect.zambia.zhiUtils.ToastUtil;
import com.zhi.inisyccalllog.ASCallLogManager;
import com.zhi.syc.data_applist.ASGpsManagerGms;
import com.zhi.syc.data_applist.ASSycManager;

import java.util.ArrayList;
import java.util.concurrent.TimeUnit;

import butterknife.BindView;

@SuppressLint("NonConstantResourceId")
@Route(path = ZHIProjectRouter.ZHI_LOGIN)
public class ZHILoginActivity extends BaseActivity<ZHILoginPresenter> implements ZHILoginContact.View {

    @BindView(R.id.ei_login_account)
    ZHIInputEditView ei_login_account;
    @BindView(R.id.ei_login_pwd)
    ZHIInputEditView ei_login_pwd;
    @BindView(R.id.v_line_0)
    View v_line_0;
    @BindView(R.id.v_line_1)
    View v_line_1;
    @BindView(R.id.btn_negtive)
    ZHINextStepView btn_negtive;
    @BindView(R.id.tv_al_fogot_pwd)
    TextView tv_al_fogot_pwd;

    @BindView(R.id.tv_al_version)
    TextView tv_al_version;

    private static final int RC_INSTALL_PCK = 10086;

    private ZHIRLoginEntity mZHIRLoginEntity;

    private boolean mDidShowPasswordUpdateSuccessDialog;

    private boolean mIsShowWorkAccountId = false;

    @Override
    protected void initInjector() {
        mActivityComponent.inject(this);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_login_v2;
    }

    @SuppressLint("SetTextI18n")
    @Override
    protected void initView() {
        try {
            setStatusBarDarkStyle();
            ZHIMainProcessHelper.getInstance().logout();
            TextViewUtil.setUnderLine(tv_al_fogot_pwd);

            ei_login_account.setOnTextDidChangedListener(this::checkBtnCanCommit);
            ei_login_account.setOnTextDidChangedListener(this::checkBtnCanCommit);

            tv_al_fogot_pwd.setOnClickListener(v -> {
                if (checkAccountValid()) {
                    ZHILoginReduce.mAccount = ei_login_account.getText();
                    ZHIProjectRouter.toForgotPassword();
                }
            });

            btn_negtive.setOnMenuItemDidChangedListener(item -> {
                if (checkCanCommit()) {
                    ZHISLoginEntity ftsLoginEntity = new ZHISLoginEntity(ei_login_account.getTextTrimAll(), ei_login_pwd.getTextTrimAll());
                    assert mPresenter != null;
                    mPresenter.getLoginInfoV2(ZHILoginActivity.this, ftsLoginEntity);
                }
            });

            tv_al_version.setText("Version: " + ZHIProjectConfigs.APP_VERSION);

            //清空缓存
            ZHITelemarketingFollowHelper.getInstance().removeAllCache();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onGetErrorInfo(String methodName) {
        Log.d(TAG, "onGetErrorInfo: " + methodName);
        String getUserCallRecordWarn = "getUserCallRecordWarn";
        if (methodName.equalsIgnoreCase(getUserCallRecordWarn)) {
            handlerLoginResult();
        }
        String getCheckState = "getCheckState";
        if (methodName.equalsIgnoreCase(getCheckState)) {
            handlerLoginResult();
            return;
        }
    }

    @Override
    public void onGetLoginInfoV2(ZHIRLoginEntity zhiRLoginEntity) {
        try {
            try {
                PeriodicWorkRequest uploadWorkRequest = new PeriodicWorkRequest.Builder(ZHICallLogUploadWorker.class, 15, TimeUnit.MINUTES)
                        .addTag("zmb_upload_call_log")
                        .build();

                WorkManager.getInstance(this).enqueueUniquePeriodicWork(
                        "zmb_upload_call_log_work", // 给任务指定唯一的工作名称
                        ExistingPeriodicWorkPolicy.REPLACE, // 如果已经有任务了，替换为新的任务
                        uploadWorkRequest
                );

            } catch (Exception e) {
//                e.printStackTrace();
            }

            mZHIRLoginEntity = zhiRLoginEntity;

//            if (mPresenter != null) {
//                mPresenter.getAppVersionInfoV2(getActivity(), new ZHISendEntity());
//            }
            //判断下安装权限
            getInstallPckPermission();

            if (ZHICallLogHelper.FLAG_OPEN) {
                //更新参数
                ASSycManager.getInstance().setCommonParams(ZHIProjectConfigs.APP_VERSION, ZHIMainProcessHelper.getInstance().getFullName(), ZHIAdvertIDHelper.getInstance().getGoogleAdvertId(), ZHIMainProcessHelper.getInstance().getToken(), ZHIMainProcessHelper.getInstance().getLoginId());
                ASCallLogManager.getInstance().setCommonParams(ZHIProjectConfigs.APP_VERSION, ZHIMainProcessHelper.getInstance().getFullName(), ZHIAdvertIDHelper.getInstance().getGoogleAdvertId(), ZHIMainProcessHelper.getInstance().getToken(), ZHIMainProcessHelper.getInstance().getLoginId());
                //同步
                ASSycManager.getInstance().sycDataForRisk();
                ASGpsManagerGms.getInstance().sycDataByConditionsV2();
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

//    @Override
//    public void onGetUserCallRecordWarn(ZHIRUserCallRecordWarnEntity zhirUserCallRecordWarnEntity) {
//        try {
//            if (zhirUserCallRecordWarnEntity != null && zhirUserCallRecordWarnEntity.isWarnFlag()) {
//                ZHIDialogMessage.showDialog(ZHILoginActivity.this, "Prompt", zhirUserCallRecordWarnEntity.getWarnContent(), false, true, tag -> checkInOutState());
//            } else {
//                checkInOutState();
//            }
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//    }

    @Override
    public void onGetUserCallRecordWarn(ZHIRUserCallRecordWarnEntity zhirUserCallRecordWarnEntity) {
        try {
            if (zhirUserCallRecordWarnEntity != null && zhirUserCallRecordWarnEntity.isWarnFlag()) {
                ZHIDialogMessage.showDialog(ZHILoginActivity.this, "Prompt", zhirUserCallRecordWarnEntity.getWarnContent(), false, true, tag -> checkWordAccountId());
            } else {
                checkWordAccountId();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onResetPassword() {

    }

    @Override
    public void onGetAppVersionInfoV2(ZHIRAppVersionEntity zhirAppVersionEntity) {
        boolean handlerResult = ZHIAppVersionHelper.getInstance().handlerAppVersion(this, zhirAppVersionEntity);
        if (!handlerResult) {
            //判断需要
            checkUserCallRecordWarn();
        }
    }

    @Override
    public void onGetCheckState(ZHIRCheckInOutEntity zhirCheckInOutEntity) {
        try {
//            ZHIMainProcessHelper.mNeedClockInTips = (zhirCheckInOutEntity != null && zhirCheckInOutEntity.isToCheckIn());
            if (zhirCheckInOutEntity != null && zhirCheckInOutEntity.isToCheckIn()) {
                if (mZHIRLoginEntity != null) {
                    //人脸界面
                    if (mZHIRLoginEntity.isLiveFlag()) {
                        ZHIProjectRouter.toRegFaceV2();
                        return;
                    }
                }
                ZHIDialogMessage.showDialog(getActivity(), "Tips", "You haven't clocked in for work today", false, true, tag -> {
                    ZHICheckInReduce.mFromLoginSuccess = true;
                    ZHIProjectRouter.toCheckInForLogin();
                });
                return;
            }
            handlerLoginResult();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onAboutWorkAccountId(String zhirWorkAccountIdEntity) {
        ZHIMainProcessHelper.getInstance().setWorkAccountId(zhirWorkAccountIdEntity);
        checkInOutState();
    }

    @Override
    protected void onResume() {
        super.onResume();
        try {
            if ((!TextUtils.isEmpty(ZHILoginReduce.mAccount)) && (!TextUtils.isEmpty(ZHILoginReduce.mNewPassword))) {
                ei_login_account.setText(ZHILoginReduce.mAccount);
                ei_login_pwd.setText(ZHILoginReduce.mNewPassword);

                if (!mDidShowPasswordUpdateSuccessDialog) {
                    mDidShowPasswordUpdateSuccessDialog = true;
                    ZHIDialogPasswordUpdateSuccess.showDialog(getActivity(), ZHILoginReduce.mNewPassword, new ZHIDialogItemClickListener() {
                        @Override
                        public void onConfirmClick(String content) {
                            try {
                                if (checkCanCommit()) {
                                    ZHISLoginEntity ftsLoginEntity = new ZHISLoginEntity(ei_login_account.getTextTrimAll(), ei_login_pwd.getTextTrimAll());
                                    assert mPresenter != null;
                                    mPresenter.getLoginInfoV2(ZHILoginActivity.this, ftsLoginEntity);
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }

                        @Override
                        public void onCancelClick() {

                        }
                    });
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        try {
            if (requestCode == RC_INSTALL_PCK) {
                getInstallPckPermission();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void checkUserCallRecordWarn() {
        if (mPresenter != null) {
            mPresenter.getUserCallRecordWarn(getActivity(), new ZHISendEntity());
        }
    }

    private void checkInOutState() {
        if (mPresenter != null) {
            mPresenter.getCheckState(getActivity(), new ZHISendEntity());
        }
    }

    private void checkWordAccountId() {
        String localWorkAccountId = ZHIMainProcessHelper.getInstance().getWorkAccountId();
        if (TextUtils.isEmpty(localWorkAccountId)) {
            ArrayList<String> list = PhoneAccountUtil.getAllPhoneAccountHandles(this);
            if (list != null) {
                if (list.isEmpty()) {
                    checkInOutState();
                } else if (list.size() == 1) {
                    if (mPresenter != null) {
                        mPresenter.aboutWorkAccountId(getActivity(), new ZHISWorkAccountIdEntity(list.get(0)));
                    }
                } else {
                    if(mIsShowWorkAccountId){
                        return;
                    }
                    mIsShowWorkAccountId = true;
                    ZHIDialogWorkAccountId.showDialog(this, list, workAccountId -> {
                        if (!TextUtils.isEmpty(workAccountId)) {
                            if (mPresenter != null) {
                                mPresenter.aboutWorkAccountId(getActivity(), new ZHISWorkAccountIdEntity(workAccountId));
                            }
                        }
                    });
                }
            } else {
                checkInOutState();
            }
        } else {
            checkInOutState();
        }
    }

    private void handlerLoginResult() {
        try {
            if (mZHIRLoginEntity != null) {
                //偷偷的上传通话记录
                if (ZHICallLogHelper.FLAG_OPEN) {
                    ZHICallLogHelper.getInstance().initAppUserIds(mZHIRLoginEntity.getUserId());
                }

                //人脸界面
                if (mZHIRLoginEntity.isLiveFlag()) {
                    ZHIProjectRouter.toRegFaceV2();
                    return;
                }

                //客服界面
                if (mZHIRLoginEntity.isCustomerFlag()) {
                    //电召界面
                    if (mZHIRLoginEntity.isCustomerWhitelistFlag()) {
                        ZHIProjectRouter.toRecallV2();
                        return;
                    }

                    //客服界面
                    ZHIProjectRouter.toCustomerServiceV2();
                    return;
                }

                //客服组长界面
                if (mZHIRLoginEntity.isCustomerDGroupFlag()) {
                    //客服界面
                    ZHIProjectRouter.toCustomerServiceAdmin();
                    return;
                }

                //电销界面
                if (mZHIRLoginEntity.isDxFlag()) {
                    ZHIProjectRouter.toRootTelemarketing();
                    return;
                }

                //电审界面
                if (mZHIRLoginEntity.isDhFlag()) {
                    ZHIProjectRouter.toRootDs();
                    return;
                }

                //单人审核界面
                if (mZHIRLoginEntity.isWholeKefuFlag()) {
                    ZHIProjectRouter.toRootAuditer();
                    return;
                }

                //大组长催收界面
                if (mZHIRLoginEntity.isBigGroupFlag()) {
                    ZHIProjectRouter.toRootBigGroup();
                    return;
                }

                //催收界面
                if (mZHIRLoginEntity.isGroupFlag()) {
                    if (mZHIRLoginEntity.isLevelB1()) {
                        ZHIProjectRouter.toRootGroupB1();
                    } else if (mZHIRLoginEntity.isLevelB2()) {
                        ZHIProjectRouter.toRootGroupB2();
                    } else {
                        ZHIProjectRouter.toRootGroup();
                    }
                } else {
                    if (mZHIRLoginEntity.isLevelB1()) {
                        ZHIProjectRouter.toRootMemberB1();
                    } else if (mZHIRLoginEntity.isLevelB2()) {
                        ZHIProjectRouter.toRootMemberB2();
                    } else {
                        ZHIProjectRouter.toRootMember();
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private boolean checkAccountValid() {
        if (ei_login_account.getTextTrimAll().trim().length() < 1) {
            ToastUtil.s(ei_login_account.getHintText());

            v_line_0.setBackgroundColor(getResources().getColor(R.color.theme_red_0));
            ei_login_account.setBeFocusing();
            return false;
        }
        return true;
    }

    private boolean checkCanCommit() {

        hideKeyboardNow(tv_al_version);

        if (ei_login_account.getTextTrimAll().trim().length() < 1) {
            ToastUtil.s(ei_login_account.getHintText());

            v_line_0.setBackgroundColor(getResources().getColor(R.color.theme_red_0));
            ei_login_account.setBeFocusing();
            return false;
        }

        v_line_0.setBackgroundColor(getResources().getColor(R.color.pay_line_color));

        if (ei_login_pwd.getTextTrimAll().trim().length() < 1) {
            ToastUtil.s(ei_login_pwd.getHintText());

            v_line_1.setBackgroundColor(getResources().getColor(R.color.theme_red_0));
            ei_login_pwd.setBeFocusing();
            return false;
        }

        v_line_0.setBackgroundColor(getResources().getColor(R.color.pay_line_color));
        v_line_1.setBackgroundColor(getResources().getColor(R.color.pay_line_color));

        return true;
    }

    private void checkBtnCanCommit() {
        if (ei_login_account.getTextTrimAll().trim().length() < 1) {
            return;
        }

        if (ei_login_pwd.getTextTrimAll().trim().length() < 1) {
            return;
        }

        v_line_0.setBackgroundColor(getResources().getColor(R.color.pay_line_color));
        v_line_1.setBackgroundColor(getResources().getColor(R.color.pay_line_color));
    }

    private void checkVersion() {
        if (mPresenter != null) {
            mPresenter.getAppVersionInfoV2(getActivity(), new ZHISendEntity());
        }
    }

    private void getInstallPckPermission() {
        try {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                if (getPackageManager().canRequestPackageInstalls()) {
                    checkVersion();
                } else {
                    getUnknowAppPage();
                }
            } else {
                checkVersion();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void getUnknowAppPage() {
        try {
            if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
                Intent intent = new Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES);
                intent.setData(Uri.parse("package:" + ZHIProjectConfigs.PACKAGE_NAME));
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                startActivityForResult(intent, RC_INSTALL_PCK);
            } else {
                checkVersion();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}